﻿using WeDonekRpc.CacheClient.Config;
using WeDonekRpc.CacheClient.Interface;
using WeDonekRpc.CacheClient.Redis;

namespace WeDonekRpc.CacheClient
{
    /// <summary>
    /// 缓存服务
    /// </summary>
    public class RpcCacheService
    {
        private static int _VerNum = 0;
        //已初始化的缓存
        private static int _InitCache = 0;

        internal static CacheType DefCacheType
        {
            get;
            private set;
        }
        /// <summary>
        /// 设置缓存版本
        /// </summary>
        /// <param name="num"></param>
        public static void SetVerNum (int num)
        {
            _VerNum = num;
        }
        /// <summary>
        /// 初始化缓存服务
        /// </summary>
        /// <param name="sysKey">缓存隔离键</param>
        /// <param name="memcached">Memcached服务地址</param>
        /// <param name="redis">redis服务地址</param>
        public static void Init (CacheConfig config, CacheType defType)
        {
            _SysKey = config.SysKey;
            DefCacheType = defType;
            CacheTimeConfig.Init();
            if (config.Redis != null && ( 4 & _InitCache ) != 4)
            {
                if (RedisHelper.InitCache(config.Redis))
                {
                    _InitCache += 4;
                }
            }
            if (config.Memcached != null && ( 2 & _InitCache ) != 2)
            {
                if (Memcached.MemcachedCache.InitCache(config.Memcached))
                {
                    _InitCache += 2;
                }
            }
        }
        public static bool CheckIsInit (CacheType type)
        {
            if (type == CacheType.Memcached)
            {
                return ( 2 & _InitCache ) == 2;
            }
            else if (type == CacheType.Redis)
            {
                return ( 4 & _InitCache ) == 4;
            }
            return true;
        }


        private static string _SysKey = null;
        internal static string FormatKey (string key)
        {
            return string.Join("_", key, _SysKey, _VerNum);
        }



        public static IRedisController GetRedis ()
        {
            return new RedisCacheController();
        }
        public static void Close ()
        {
            RedisHelper.Close();
            Memcached.MemcachedCache.Close();
            Local.LocalCache.Close();
            CacheTimeConfig.Close();
        }


    }
}
